﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SharePoint2007Migration
{
    public static class LogHelper
    {
        private const string LOG_FILE_NAME_FORMAT = "{0:yyyyMMdd HHmmss}.txt";
        private const string LOG_DATETIME_ENTRY = "{0:yyyy/MM/dd HH:mm:ss.fff}";

        private readonly static string logFileFullPath;

        static LogHelper()
        {
            logFileFullPath = Path.Combine(ConfigHelper.LogFilePath, string.Format(LOG_FILE_NAME_FORMAT, DateTime.Now));
        }


        public static void TraceDebug(string debugInfo, LogVerboseLevel logVerboseLevel)
        {
            try
            {
                if (ConfigHelper.VerboseLevel <= logVerboseLevel)
                    WriteToFile(debugInfo);
            }
            catch { }
        }


        public static void TraceDebug(string debugInfo)
        {
            TraceDebug(debugInfo, ConfigHelper.VerboseLevel);
        }
   
        public static void TraceDebugImportant(string debugInfo)
        {
            TraceDebugImportant(String.Concat("## ", debugInfo), ConfigHelper.VerboseLevel);
        }

        public static void TraceDebugImportant(string debugInfo, LogVerboseLevel logVerboseLevel)
        {
            TraceDebug(String.Concat("## ", debugInfo), logVerboseLevel);
        }



        public static void TraceError(Exception exc)
        {
            try
            {
                string errorMessage = string.Concat("################### EXCEPTION ####################### ",
                    new StackTrace().GetFrame(1).GetMethod().Name, " : ", exc.Message);
                TraceDebug(errorMessage);

            }
            catch
            {}
            
        }

        private static void WriteToFile(string debugInfo)
        {
            using (TextWriter textWriter = new StreamWriter(logFileFullPath, true))
            {
                StringBuilder stringBuilder = new StringBuilder();

                stringBuilder.Append(string.Format(LOG_DATETIME_ENTRY, DateTime.Now));
                stringBuilder.Append(" - ");
                stringBuilder.Append(new StackTrace().GetFrame(2).GetMethod().Name);
                stringBuilder.Append(" ");
                stringBuilder.Append(debugInfo);

                textWriter.WriteLine(stringBuilder.ToString());
                textWriter.Close();
            }
        }


    }

}
